package com.example.plugin;

import android.content.Context;
import android.util.Log;

import java.lang.reflect.Array;
import java.lang.reflect.Field;

import dalvik.system.DexClassLoader;


public class LoadUtils {
    public static void loadClass(Context context) {
        try {
            ClassLoader pathClassLoader = context.getClassLoader();
            Class<?> baseDexClassLoaderClass = Class.forName("dalvik.system.BaseDexClassLoader");
            Field pathListField = baseDexClassLoaderClass.getDeclaredField("pathList");
            pathListField.setAccessible(true);
            Object dexPathListClass = pathListField.get(pathClassLoader);

            Class<?> dexPathList = Class.forName("dalvik.system.DexPathList");
            Field dexElementsField = dexPathList.getDeclaredField("dexElements");
            dexElementsField.setAccessible(true);
            Object[] hostElements = (Object[]) dexElementsField.get(dexPathListClass);

            DexClassLoader dexClassLoader = new DexClassLoader("/sdcard/pluginapp-debug.apk", context.getCacheDir().getAbsolutePath(), null, context.getClassLoader());

            Object pluginDexPathListClass = pathListField.get(dexClassLoader);
            Object[] pluginElements = (Object[]) dexElementsField.get(pluginDexPathListClass);
            Object[] mainElements = (Object[]) Array.newInstance(hostElements.getClass().getComponentType(), hostElements.length + pluginElements.length);
            System.arraycopy(hostElements, 0, mainElements, 0, hostElements.length);
            System.arraycopy(pluginElements, 0, mainElements, hostElements.length, pluginElements.length);
            dexElementsField.set(dexPathListClass, mainElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
